<?php

namespace app\common\service;

use think\facade\Cache;
use think\facade\Env;
use think\facade\Route;
use think\Service;

class AddonService extends Service
{
    const ADDONS_STATE_KEY = 'addons_state';//插件状态缓存key
    const ADDONS_ALL_KEY = 'addons_all';//插件列表key
    protected $addons = [];//插件列表
    protected $url_array = [];//当前url
    public function register()
    {
// 插件目录
        ! defined('ADDON_PATH') && define('ADDON_PATH', app()->getRootPath().'addons'.DIRECTORY_SEPARATOR);
        ! defined('DS') && define('DS', DIRECTORY_SEPARATOR);
        // 如果插件目录不存在则创建
        if (! is_dir(ADDON_PATH)) {
            @mkdir(ADDON_PATH, 0755, true);
        }
        $this->webHandAddons();
    }
    public function boot()
    {

    }
    protected function webHandAddons()
    {
        $url = request()->baseUrl();
        $url = str_replace('/index.php', '', $url);
        $url_array = explode('/', $url);
        $url_array = array_filter($url_array);
        $url_array = array_values($url_array);
        $this->url_array = $url_array;
        $this->addonsHand();
    }
    protected function addonsHand()
    {
        $addons = get_addons_list();
        $this->addons = $addons;
        app()->request->addons = $addons;
        if(!empty($addons)){
            $files = $this->get_addons_files();
            $middleware = [];
            foreach ($files as $key => $value){
                // 服务注册
                if(!empty($value['base_service'])){
                    app()->register($value['base_service']);
                }
                // 中间件注册
                if(!empty($value['base_middleware'])){
                    $middleware = array_merge($middleware,$value['base_middleware']);
                }
                // 事件注册
                if(!empty($value['base_event'])){
                    if(!empty($value['base_event']['bind'])){
                        app()->event->bind($value['base_event']['bind']);
                    }
                    if(!empty($value['base_event']['listen'])){
//                        print_r($value['base_event']['listen']);
                        app()->event->listenEvents($value['base_event']['listen']);
                    }
                    if(!empty($value['base_event']['subscribe'])){
                        app()->event->subscribe($value['base_event']['subscribe']);
                    }
                }
                if(request()->isCli()){
                    if(!empty($value['base_command'])){
                        $this->commands($value['base_command']);
                    }
                }
            }
            if(isset($this->url_array[0])&&$this->url_array[0]==='addons'){
                Route::rule('addons/<addons>/<module>/<controller>/<action>',"\\app\\common\\core\\AddonRoute::execute")->middleware($middleware);
            }
        }
    }
    protected function get_addons_files()
    {
        $addons_list = $this->addons;
        if(empty($addons_list)){
            return [];
        }
        $cache = [];
        foreach ($addons_list as $key => $value) {
            $cache[$value] = [];
            $addon_value_dir = app()->getRootPath().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR;
            // 服务配置
            $service = $addon_value_dir.'service.php';
            if(is_file($service)){
                $cache[$value]['base_service'] = require $service;
            }
            // 中间件配置
            $middleware = $addon_value_dir.'middleware.php';
            if(is_file($middleware)){
                $cache[$value]['base_middleware'] = require $middleware;
            }
            // 事件配置
            $event = $addon_value_dir.'event.php';
            if(is_file($event)){
                $cache[$value]['base_event'] = require $event;
            }
            // 命令配置
            $command = $addon_value_dir.'command.php';
            if(is_file($command)){
                $cache[$value]['base_command'] = require $command;
            }
            //函数文件直接引入
            $common = $addon_value_dir.'common.php';
            if(is_file($common)){
                include $common;
            }
            // 路由文件直接引入
            $route = $addon_value_dir.'route.php';
            if(is_file($route)){
//                    echo '有路由文件';
                include $route;
            }
            $childFiles = \app\common\core\FileHand::init()->get_dir_path($addon_value_dir,'dir',[
                'common',
                'route',
                'service',
                'middleware',
                'event',
                'command'
            ],[

            ],false,true);
            foreach ($childFiles as $values){
                $addon_child_dir = $addon_value_dir.$values.DIRECTORY_SEPARATOR;
                $child_service = $addon_child_dir.'service.php';
                if(is_file($child_service)){
                    $cache[$value]['child_service'][$values] = require $child_service;
                }
                $child_middleware = $addon_child_dir.'middleware.php';
                if(is_file($child_middleware)){
                    $cache[$value]['child_middleware'][$values] = require $child_middleware;
                }
                $child_event = $addon_child_dir.'event.php';
                if(is_file($child_event)){
                    $cache[$value]['child_event'][$values] = require $child_event;
                }
                $child_command = $addon_child_dir.'command.php';
                if(is_file($child_command)){
                    $cache[$value]['child_command'][$values] = require $child_command;
                }
                $child_common = $addon_child_dir.'common.php';
                if(is_file($child_common)){
                    include $child_common;
                }
                $child_route = $addon_child_dir.'route.php';
                if(is_file($child_route)){
                    include $child_route;
                }
            }
        }
        return $cache;
    }

    /**
     * 清理插件缓存
     * @return true
     */
    public function clearAddonsCache()
    {
        $key_array = [
            self::ADDONS_STATE_KEY,
            self::ADDONS_ALL_KEY,
        ];
        foreach ($key_array as $key){
            Cache::delete($key);
        }
        return true;
    }

}